import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class ImportDialog extends JDialog {
	private final Main main;
	public ImportDialog(Main owner) {
		super(owner);
		main=owner;
		setTitle("匯入");
		setSize(400, 150);
		setLocation(owner.getX()+(owner.getWidth()-this.getWidth())/2, 
				    owner.getY()+(owner.getHeight()-this.getHeight())/2);
		setLayout(new BorderLayout());
		
		final JLabel desc=new JLabel("匯入 .csv 檔至資料庫:");
		desc.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		add(desc, BorderLayout.NORTH);
		
		final JLabel fileLabel=new JLabel("檔案路徑:");
		final JTextField fileField=new JTextField(25);
		final JButton fileButton=new JButton("瀏覽...");
		fileButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				final File preFile=new File(fileField.getText());
				JFileChooser fc=null;
				if(preFile.exists()) {
					fc=new JFileChooser(preFile);
				} else {
					fc=new JFileChooser();
				}
				final int r=fc.showOpenDialog(ImportDialog.this);
				if (r == JFileChooser.APPROVE_OPTION) {
		            final File file = fc.getSelectedFile();
		            fileField.setText(file.getAbsolutePath());
		        }
			}
		});
		final JPanel filePanel=new JPanel();
		filePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
		filePanel.add(fileLabel);
		filePanel.add(fileField);
		filePanel.add(fileButton);
		add(filePanel, BorderLayout.CENTER);
		
		final JCheckBox replaceBox=new JCheckBox("取代舊資料");
		final JButton okButton=new JButton("確定");
		okButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				final File f=new File(fileField.getText());	//>>> dangerous
				main.clearResults();
				Main.stuDB.execute(
"CALL SYSCS_UTIL.SYSCS_IMPORT_DATA(null, 'STUDENTS', null, '2,3,6,8', ?, null, null, 'ms950', ?)",
f.getAbsolutePath(),
replaceBox.isSelected()?1:0);
				main.searchPane.search();
				setVisible(false);
			}
		});
		final JButton cancelButton=new JButton("取消");
		cancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				setVisible(false);
			}
		});
		final JPanel confirmPanel=new JPanel();
		confirmPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		confirmPanel.add(replaceBox);
		confirmPanel.add(okButton);
		confirmPanel.add(cancelButton);
		add(confirmPanel, BorderLayout.SOUTH);
	}
}
